package it.demosms.service.impl;

import com.auth0.jwt.JWT;
import it.demosms.constant.UserConstant;
import it.demosms.dao.UserDao;
import it.demosms.pojo.dto.LoginUserDTO;
import it.demosms.pojo.dto.RegisterUserDTO;
import it.demosms.pojo.orm.User;
import it.demosms.service.ifac.UserService;
import it.demosms.util.Result;
import it.demosms.util.ResultStatusEM;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * 用户注册登录
 *
 * @author 季鑫利
 */
@Service
public class UserServiceImpl implements UserService {

    /**
     * 日志
     */
    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * token获取接口实现
     */
    @Autowired
    private TokenServiceImpl tokenService;

    /**
     * Redis
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * dao
     */
    @Autowired
    private UserDao userDao;

    /**
     * smsKey
     */
    private String smsKey = UserConstant.PHONE;

    /**
     * 注册用户
     *
     * @param registerUserDTO 用户信息
     * @author 季鑫利
     */
    @Override
    public boolean saveUser(RegisterUserDTO registerUserDTO, String smsCode) {
        //比较短信验证码
        //获取系统短信验证码
        if (registerUserDTO == null) {
            return false;
        }
        RegisterUserDTO registerUser = new RegisterUserDTO();
        smsKey = UserConstant.PHONE + registerUserDTO.getPhone();
        //密码加密
        String password = DigestUtils.md5Hex(registerUserDTO.getPassword());
        registerUser.setUsername(registerUserDTO.getUsername());
        registerUser.setPhone(registerUserDTO.getPhone());
        registerUser.setPassword(password);
        //获取缓存中的验证码
        String sysCode = (String) redisTemplate.boundValueOps(smsKey).get();
        if (sysCode == null) {
            throw new RuntimeException("验证码未发送或已过期");
        }
        if (!smsCode.equals(sysCode)) {
            throw new RuntimeException("验证码不正确");
        }
        if (registerUserDTO.getUsername() == null) {
            //用户名为空时，把手机号作为用户名
            registerUserDTO.setUsername(registerUserDTO.getPhone());
        }
        if (userDao.queryByPhone(registerUserDTO.getPhone()) != null) {
            throw new RuntimeException("该手机号已注册");
        }
        return userDao.saveUser(registerUser) > 0;
    }

    @Override
    /**
     * 用户登录
     * @param loginUserDTO 用户登录信息
     * @author 季鑫利
     */
    public Result login(LoginUserDTO loginUserDTO) {
        Result result = new Result();
        String smsKey = UserConstant.PHONE + loginUserDTO.getPhone();
        String sysCode = (String) redisTemplate.boundValueOps(smsKey).get();
        String password = DigestUtils.md5Hex(loginUserDTO.getPassword());
        if (!loginUserDTO.getSmsCode().equals(sysCode)) {
            result.setMessage("验证码错误或不存在");
            result.setStatus(ResultStatusEM.ERROR);
            return result;
        }
        User userForBase = userDao.queryByPhone(loginUserDTO.getPhone());
        if (userForBase == null) {
            result.setMessage("登录失败,用户不存在");
            result.setStatus(ResultStatusEM.ERROR);
            return result;
        }
        try {
            if (!userForBase.getPassword().equals(password)) {
                result.setMessage("登录失败,密码错误");
                result.setStatus(ResultStatusEM.ERROR);
                return result;
            }
        } catch (Exception e) {
            log.error("密码不能为空：" + e.getMessage());
        }
        // 验证成功后，要从redis中删除验证码
        redisTemplate.delete(smsKey);
        String token = tokenService.getToken(userForBase);
        redisTemplate.opsForValue().set(UserConstant.SYS_TOKEN, token);
        result.setStatus(ResultStatusEM.OK);
        result.setData(token);
        return result;
    }

    /**
     * 根据手机号查询
     * @param phone 手机号
     * @return 用户
     * @author 季鑫利
     */
    @Override
    public User queryByPhone(String phone) {
        return userDao.queryByPhone(phone);
    }

    /**
     * 验证token
     * @param token token信息
     * @return false无token
     */
    @Override
    public boolean checkToken(String token) {
        String redisToken = (String) redisTemplate.opsForValue().get(UserConstant.SYS_TOKEN);
        if (!token.equals(redisToken)) {
            return false;
        }

        return true;
    }

    /**
     * 获取token中的user id
     *
     * @param token
     * @author 季鑫利
     */
    @Override
    public Integer getUserIdByToken(String token) {
        return JWT.decode(token).getClaim("userID").asInt();
    }

}
